<style>
    #ui-chart-colors input[type="color"] {
        font-weight: bold;
    }
    #ui-chart-colors input[type="color"]::-webkit-color-swatch,
    #ui-chart-colors input[type="color"]::-moz-color-swatch {
        border: none;
    }

    .node-chart-properties {
        display: inline-flex;
        align-items: center;
        width: 70%;
        gap: 16px;
        flex-wrap: wrap;
    }
    .node-chart-properties .red-ui-typedInput-container {
        flex-grow: 1;
    }
    .node-chart-property {
        display: flex;
        gap: 8px;
        align-items: center;
        flex-grow: 1;
    }
    .node-chart-property label {
        margin: 0;
    }
    .node-chart-property#node-container-category {
        width: 100%;
    }
</style>

<script type="text/javascript">
    (function () {
        function hexToRgb (hex) {
            const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
            return result
                ? {
                    r: parseInt(result[1], 16),
                    g: parseInt(result[2], 16),
                    b: parseInt(result[3], 16)
                }
                : null
        }

        RED.nodes.registerType('ui-chart', {
            category: RED._('@flowfuse/node-red-dashboard/ui-base:ui-base.label.category'),
            color: RED._('@flowfuse/node-red-dashboard/ui-base:ui-base.colors.medium'),
            defaults: {
                group: { type: 'ui-group', required: true },
                name: { value: '' },
                label: { value: 'chart' },
                order: { value: Number.MAX_SAFE_INTEGER },
                chartType: { value: 'line' },
                category: { value: 'topic' },
                categoryType: { value: 'msg' },
                xAxisProperty: { value: null },
                xAxisPropertyType: { value: 'msg' },
                xAxisType: { value: 'time' },
                yAxisProperty: { value: null },
                ymin: { value: '', validate: function (value) { return value === '' || RED.validators.number() } },
                ymax: { value: '', validate: function (value) { return value === '' || RED.validators.number() } },
                action: { value: 'append' },
                pointShape: { value: 'circle' },
                pointRadius: { value: 4 },
                showLegend: { value: true },
                removeOlder: { value: 1, validate: RED.validators.number(), required: true },
                removeOlderUnit: { value: '3600', required: true },
                removeOlderPoints: { value: '', validate: function (value) { return value === '' || RED.validators.number() } },
                colors: { value: ['#1F77B4', '#AEC7E8', '#FF7F0E', '#2CA02C', '#98DF8A', '#D62728', '#FF9896', '#9467BD', '#C5B0D5'] },
                width: {
                    value: 6,
                    validate: function (v) {
                        const width = v || 0
                        const currentGroup = $('#node-input-group').val() || this.group
                        const groupNode = RED.nodes.node(currentGroup)
                        const valid = !groupNode || +width <= +groupNode.width
                        $('#node-input-size').toggleClass('input-error', !valid)
                        return valid
                    }
                },
                height: { value: 8 },
                className: { value: '' }
            },
            inputs: 1,
            outputs: 1,
            inputLabels: function () { return this.chartType },
            outputLabels: ['chart state'],
            icon: 'font-awesome/fa-line-chart',
            align: 'right',
            paletteLabel: 'chart',
            label: function () {
                return this.name || (~this.label.indexOf('{' + '{') ? null : this.label) || this.mode + ' chart'
            },
            labelStyle: function () { return this.name ? 'node_label_italic' : '' },
            oneditprepare: function () {
                const propertyType = { value: 'property', label: RED._('@flowfuse/node-red-dashboard/ui-chart:ui-chart.label.key') }

                // if this groups parent is a subflow template, set the node-config-input-width and node-config-input-height up
                // as typedInputs and hide the elementSizer (as it doesn't make sense for subflow templates)
                if (RED.nodes.subflow(this.z)) {
                    // change inputs from hidden to text & display them
                    $('#node-input-width').attr('type', 'text')
                    $('#node-input-height').attr('type', 'text')
                    $('div.form-row.nr-db-ui-element-sizer-row').hide()
                    $('div.form-row.nr-db-ui-manual-size-row').show()
                } else {
                    // not in a subflow, use the elementSizer
                    $('div.form-row.nr-db-ui-element-sizer-row').show()
                    $('div.form-row.nr-db-ui-manual-size-row').hide()
                    $('#node-input-size').elementSizer({
                        width: '#node-input-width',
                        height: '#node-input-height',
                        group: '#node-input-group'
                    })
                }

                // use jQuery UI tooltip to convert the plain old title attribute to a nice tooltip
                $('.ui-node-popover-title').tooltip({
                    show: {
                        effect: 'slideDown',
                        delay: 150
                    }
                })

                // set value options for chart's type
                $('#node-input-chartType').typedInput({
                    type: 'chartType',
                    types: [{
                        value: 'line',
                        options: [
                            { value: 'line', label: RED._('@flowfuse/node-red-dashboard/ui-chart:ui-chart.label.line') },
                            { value: 'bar', label: RED._('@flowfuse/node-red-dashboard/ui-chart:ui-chart.label.bar') },
                            { value: 'scatter', label: RED._('@flowfuse/node-red-dashboard/ui-chart:ui-chart.label.scatter') }
                        ]
                    }],
                    typeField: '#node-input-chartTypeType'
                })

                // line    = time, linear, log
                // scatter = time, linear, log
                // bar     = categorical (or just hide)

                // provide options for x-axis type
                $('#node-input-xAxisType').typedInput()

                $('#node-input-category').typedInput({
                    default: 'msg',
                    typeField: $('#node-input-categoryType'),
                    types: ['msg', 'str', 'json', propertyType]
                })
                $('#node-input-xAxisProperty').typedInput({
                    default: propertyType.value,
                    typeField: $('#node-input-xAxisPropertyType'),
                    types: [propertyType]
                })
                $('#node-input-yAxisProperty').typedInput({
                    default: propertyType.value,
                    typeField: $('#node-input-yAxisPropertyType'),
                    types: [propertyType]
                })

                $('#node-input-pointShape').typedInput({
                    type: 'pointShape',
                    default: 'circle',
                    typeField: $('#node-input-pointShapeType'),
                    types: [{
                        value: 'circle',
                        options: [
                            { value: 'circle', label: RED._('@flowfuse/node-red-dashboard/ui-chart:ui-chart.label.circle') },
                            { value: 'cross', label: RED._('@flowfuse/node-red-dashboard/ui-chart:ui-chart.label.cross') },
                            { value: 'crossRot', label: RED._('@flowfuse/node-red-dashboard/ui-chart:ui-chart.label.crossRotated') },
                            { value: 'dash', label: RED._('@flowfuse/node-red-dashboard/ui-chart:ui-chart.label.dash') },
                            { value: 'line', label: RED._('@flowfuse/node-red-dashboard/ui-chart:ui-chart.label.line2') },
                            { value: 'rect', label: RED._('@flowfuse/node-red-dashboard/ui-chart:ui-chart.label.rectangle') },
                            { value: 'rectRounded', label: RED._('@flowfuse/node-red-dashboard/ui-chart:ui-chart.label.roundedRectangle') },
                            { value: 'rectRot', label: RED._('@flowfuse/node-red-dashboard/ui-chart:ui-chart.label.rotatedRectangle') },
                            { value: 'star', label: RED._('@flowfuse/node-red-dashboard/ui-chart:ui-chart.label.star') },
                            { value: 'triangle', label: RED._('@flowfuse/node-red-dashboard/ui-chart:ui-chart.label.triangle') },
                            { value: 'false', label: RED._('@flowfuse/node-red-dashboard/ui-chart:ui-chart.label.none') }
                        ]
                    }]
                })

                // handle event when chart's type is changed
                $('#node-input-chartType').on('change', (evt) => {
                    const value = $('#node-input-chartType').typedInput('value')

                    if (value === 'line' || value === 'scatter') {
                        // for line and scatter
                        // types - time, linear
                        $('#node-input-xAxisType').typedInput('types', [{
                            value: 'linear',
                            options: [
                                { value: 'time', label: RED._('@flowfuse/node-red-dashboard/ui-chart:ui-chart.label.timescale') },
                                { value: 'linear', label: RED._('@flowfuse/node-red-dashboard/ui-chart:ui-chart.label.linear') }
                            ]
                        }])
                        $('#node-input-xAxisType').typedInput('type', 'time')
                        // show x-axis property setting
                        $('#node-container-xAxisProperty').show()
                        // show x-axis limit options & points sizing
                        $('#x-axis-show').show()
                        $('#point-radius-show').show()
                    } else {
                        // for bar
                        // types - categorical
                        $('#node-input-xAxisType').typedInput('types', [{
                            value: 'linear',
                            options: [
                                { value: 'category', label: RED._('@flowfuse/node-red-dashboard/ui-chart:ui-chart.label.categorical') }
                            ]
                        }])
                        $('#node-input-xAxisType').typedInput('type', 'category')
                        // show x-axis property setting
                        $('#node-container-xAxisProperty').hide()
                        // hide x-axis limit options & points sizing
                        $('#x-axis-show').hide()
                        $('#point-radius-show').hide()
                    }
                })

                // handle event when chart's type is changed
                $('#node-input-category').change((evt) => {
                    const categoryType = $('#node-input-categoryType').val()

                    if (categoryType === 'json') {
                        // hide y-axis property setting as category will now control that
                        $('#node-container-yAxisProperty').hide()
                    } else {
                        $('#node-container-yAxisProperty').show()
                    }
                })

                // Series Color Pickers
                const setColor = function (id, value) {
                    $(id).val(value)
                    $(id).css('background-color', value)
                    const rgb = hexToRgb(value)
                    const level = ((rgb.r * 299) + (rgb.g * 587) + (rgb.b * 114)) / 1000
                    const textColor = (level >= 128) ? '#111111' : '#eeeeee'
                    $(id).css('color', textColor)
                }
                $('.series-color').on('change', function () {
                    setColor('#' + $(this).attr('id'), $(this).val())
                })
                const defaultColors = ['#1F77B4', '#AEC7E8', '#FF7F0E', '#2CA02C', '#98DF8A', '#D62728', '#FF9896', '#9467BD', '#C5B0D5']

                if (this.colors) {
                    for (let i = 0; i < this.colors.length; i++) {
                        const value = this.colors[i] || defaultColors[i]
                        setColor('#node-input-color' + (i + 1), value)
                    }
                } else {
                    for (let c = 0; c < defaultColors.length; c++) {
                        setColor('#node-input-color' + (c + 1), defaultColors[c])
                    }
                }
            },
            oneditsave: function () {
                const colors = []
                for (let i = 0; i < 9; i++) {
                    const color = $('#node-input-color' + (i + 1)).val()
                    if (color) {
                        colors.push(color)
                    }
                }
                this.colors = colors
            }
        })
    })()
</script>

<script type="text/html" data-template-name="ui-chart">
    <div class="form-row">
        <label for="node-input-name"><i class="fa fa-tag"></i> <span data-i18n="node-red:common.label.name"></label>
        <input type="text" id="node-input-name" data-i18n="[placeholder]node-red:common.label.name">
    </div>
    <div class="form-row">
        <label for="node-input-group"><i class="fa fa-table"></i> <span data-i18n="ui-chart.label.group"></span></label>
        <input type="text" id="node-input-group">
    </div>
    <div class="form-row nr-db-ui-element-sizer-row">
        <label><i class="fa fa-object-group"></i> <span data-i18n="ui-chart-group.label.size"></label>
        <button class="editor-button" id="node-input-size"></button>
    </div>
    <div class="form-row nr-db-ui-manual-size-row">
        <label><i class="fa fa-arrows-h"></i> <span data-i18n="ui-chart-group.label.width">Width</label>
        <input type="hidden" id="node-input-width">
    </div>
    <div class="form-row nr-db-ui-manual-size-row">
        <label><i class="fa fa-arrows-v"></i> <span data-i18n="ui-chart-group.label.height">Height</label>
        <input type="hidden" id="node-input-height">
    </div>
    <div class="form-row">
        <label for="node-input-label"><i class="fa fa-i-cursor"></i> <span data-i18n="ui-chart.label.label"></span></label>
        <input type="text" id="node-input-label" data-i18n="[placeholder]ui-chart.label.optionalChartTitle">
    </div>
    <div class="form-row">
        <label for="node-input-className"><i class="fa fa-code"></i> <span data-i18n="ui-chart.label.class"></span></label>
        <div style="display: inline;">
            <input style="width: 70%;" type="text" id="node-input-className" data-i18n="[placeholder]ui-chart.label.optionalCssClassNames" style="flex-grow: 1;">
            <a
                data-html="true"
                title="Dynamic Property: Send msg.class to append new classes to this widget. NOTE: classes set at runtime will be applied in addition to any class(es) set in the nodes class field."
                class="red-ui-button ui-node-popover-title"
                style="margin-left: 4px; cursor: help; font-size: 0.625rem; border-radius: 50%; width: 24px; height: 24px; display: inline-flex; justify-content: center; align-items: center;">
                <i style="font-family: ui-serif;">fx</i>
            </a>
        </div>
    </div>
    <div class="form-row" style="display: flex; align-items: center; gap: 36px;">
        <div>
            <label for="node-input-chartType"><i class="fa fa-bookmark"></i> <span data-i18n="ui-chart.label.type"></span></label>
            <input type="text" id="node-input-chartType">
            <input type="hidden" id="node-input-chartTypeType">
        </div>
        <div>
            <label style="width:auto" for="node-input-showLegend"><i class="fa fa-th-list"></i> <span data-i18n="ui-chart.label.showLegend"></span></label>
            <input type="checkbox" checked id="node-input-showLegend" style="display: inline-block; width: auto; margin: 0px 0px 0px 4px;">
        </div>
    </div>
    <div class="form-row">
        <label for="node-input-action" data-i18n="ui-chart.label.action"></label></label>
        <select id="node-input-action">
            <option value="append" data-i18n="ui-chart.label.append"></option>
            <option value="replace" data-i18n="ui-chart.label.replace"></option>
        </select>
    </div>
    <div class="form-row form-row-flex" id="point-radius-show">
        <label for="node-input-pointRadius" data-i18n="ui-chart.label.pointStyle"></label>
        <div style="margin-right: 6px;">
            <label for="node-input-pointShape" style="width: auto;" data-i18n="ui-chart.label.pointShape"></label>
            <input type="text" id="node-input-pointShape">
            <input type="hidden" id="node-input-pointShapeType">
        </div>
        <div>
            <label for="node-input-pointRadius" style="width: auto;" data-i18n="ui-chart.label.pointRadius"></label>
            <input type="number" id="node-input-pointRadius">
        </div>
    </div>
    <div class="form-row">
        <label for="node-input-xAxisType" data-i18n="ui-chart.label.xType"></label></label>
        <input type="text" id="node-input-xAxisType">
        <input type="hidden" id="node-input-xAxisTypeType">
    </div>
    <div class="form-row" id="x-axis-show">
        <label for="node-input-removeOlder" data-i18n="ui-chart.label.xLimit"></label>
        <label for="node-input-removeOlder" style="width:auto" data-i18n="ui-chart.label.last"></label>
        <input type="text" id="node-input-removeOlder" style="width:50px;">
        <select id="node-input-removeOlderUnit" style="width:100px;">
            <option value="1" data-i18n="ui-chart.label.seconds"></option>
            <option value="60" data-i18n="ui-chart.label.minutes"></option>
            <option value="3600" data-i18n="ui-chart.label.hours"></option>
            <option value="86400" data-i18n="ui-chart.label.days"></option>
            <option value="604800" data-i18n="ui-chart.label.weeks"></option>
        </select>
        <label for="node-input-removeOlderPoints" style="width:auto; margin-left:10px; margin-right:10px;" data-i18n="ui-chart.label.or"></label>
        <input type="text" id="node-input-removeOlderPoints" style="width:60px;" placeholder="1000">
        <span style="margin-left:5px;" data-i18n="ui-chart.label.points"></span>
    </div>
    <div class="form-row" id="y-axis-show">
        <label id="y-label-show" for="node-input-ymin" data-i18n="ui-chart.label.yAxis"></label>
        <label for="node-input-ymin" style="width:auto" data-i18n="ui-chart.label.min"></label>
        <input type="text" id="node-input-ymin" style="width:92px">
        <label for="node-input-ymax" style="width:auto; margin-left:20px;" data-i18n="ui-chart.label.max"></label>
        <input type="text" id="node-input-ymax" style="width:92px">
    </div>
    <div class="form-row">
        <label data-i18n="ui-chart.label.properties"></label>
        <div id="node-container-axisKeys" class="node-chart-properties">
            <div id="node-container-category" class="node-chart-property">
                <label style="width: auto" for="node-input-category" data-i18n="ui-chart.label.series"></label>
                <input style="flex-grow: 1" type="text" id="node-input-category" placeholder="topic">
                <input type="hidden" id="node-input-categoryType">
            </div>
            <div id="node-container-xAxisProperty" class="node-chart-property">
                <label style="width: auto" for="node-input-xAxisProperty">X:</label>
                <input style="flex-grow: 1" type="text" id="node-input-xAxisProperty" data-i18n="[placeholder]ui-chart.label.propertyPlaceholder">
            </div>
            <div id="node-container-yAxisProperty" class="node-chart-property">
                <label style="width: auto" for="node-input-yAxisProperty">Y:</label>
                <input style="flex-grow: 1" type="text" id="node-input-yAxisProperty" data-i18n="[placeholder]ui-chart.label.propertyPlaceholder">
            </div>
        </div>
    </div>
    <div class="form-row" id="ui-chart-colors">
        <label for="node-input-color1" data-i18n="ui-chart.label.seriesColors"></label>
        <input type="color" id="node-input-color1" class="series-color" style="width:100px;"/>
        <input type="color" id="node-input-color2" class="series-color" style="width:100px;"/>
        <input type="color" id="node-input-color3" class="series-color" style="width:100px;"/>
        <div style="margin-top:5px; margin-left:104px;">
            <input type="color" id="node-input-color4" class="series-color" style="width:100px;"/>
            <input type="color" id="node-input-color5" class="series-color" style="width:100px;"/>
            <input type="color" id="node-input-color6" class="series-color" style="width:100px;"/>
        </div>
        <div style="margin-top:5px; margin-left:104px;">
            <input type="color" id="node-input-color7" class="series-color" style="width:100px;"/>
            <input type="color" id="node-input-color8" class="series-color" style="width:100px;"/>
            <input type="color" id="node-input-color9" class="series-color" style="width:100px;"/>
        </div>
    </div>
</script>
